package com.business.user.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.business.common.constant.MessageConstant;
import com.business.common.enums.BusinessExceptionEnum;
import com.business.common.enums.ErrorEnum;
import com.business.common.exception.BusinessException;
import com.business.common.exception.CustomException;
import com.business.common.utils.FormatValidUtil;
import com.business.common.utils.StrKit;
import com.business.user.entity.Message;
import com.business.user.entity.User;
import com.business.user.entity.UserDetails;
import com.business.user.mapper.UserDetailsMapper;
import com.business.user.mapper.UserMapper;
import com.business.user.rabbitMq.RabbitMqSender;
import com.business.user.service.UserService;
import com.business.user.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


/**
 * 用户表:业务接口实现类
 *
 * @author chenjiehong
 * @date 2019-04-28 15:03:18
 * @since 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper sysUserMapper;

    @Autowired
    private UserDetailsMapper userDetailsMapper;

    @Autowired
    private RabbitMqSender rabbitMqSender;

    @Override
    @Transactional
    public User add(User sysUser, String realName) {

        //密码不能为空,快捷登陆没有密码
        if (!StrKit.isBlank(sysUser.getPassword())) {
            //加密密码
            sysUser.setPassword(Md5Util.getSaltMD5(sysUser.getPassword()));
        }
        Integer result = sysUserMapper.getOneByKey("phone", sysUser.getPhone());
        if (result != null && result > 0) {
            throw new BusinessException(BusinessExceptionEnum.USER_PHONE_EXIST);
        }

        sysUser.setState(1);
        sysUser.setRegisterType(0);//注册类型
        sysUser.setCreateTime(new Date());
        sysUser.setState(1);
        if (sysUserMapper.insert(sysUser) > 0) {
            //插入明细
            UserDetails userDetails = new UserDetails();
            userDetails.setUserId(sysUser.getId());
            userDetails.setCreateTime(new Date());
            userDetails.setRealName(realName);
            userDetailsMapper.insert(userDetails);
            sysUser = sysUserMapper.selectById(sysUser.getId());
            sysUser.setPassword(null);
            sysUser.setSessionKey(null);
            sysUser.setOpenId(null);

            return sysUser;
        } else {//未知错误
            throw new CustomException(ErrorEnum.UNKNOWN_ERROR);
        }
    }

    @Override
    @Transactional
    public User login(User sysUser, int type) {
        sysUser.setState(1);//正常
        User resultUser = null;
        switch (type) {
            default:
            case 0://默认登陆
                if (StrKit.isBlank(sysUser.getPhone())) {
                    throw new BusinessException(BusinessExceptionEnum.PHONE_NULL);
                }
                if (!FormatValidUtil.matchPhone(sysUser.getPhone())) {
                    throw new BusinessException(BusinessExceptionEnum.PHONE_PATTERN_ERROR);
                }
                if (StrKit.isBlank(sysUser.getPassword())) {
                    throw new BusinessException(BusinessExceptionEnum.PASSWORD_NULL);
                }
                User params1 = new User();
                params1.setPhone(sysUser.getPhone());
                resultUser = sysUserMapper.selectOne(params1);
                if (resultUser == null) {
                    throw new BusinessException(BusinessExceptionEnum.USER_NON_EXIST);
                }
                //用户冻结
                if (resultUser.getState() != 1) {
                    throw new BusinessException(BusinessExceptionEnum.USER_FROZEN);
                }
                boolean eqFlag = Md5Util.getSaltverifyMD5(sysUser.getPassword(), resultUser.getPassword());
                if (!eqFlag) {
                    throw new BusinessException(BusinessExceptionEnum.PASSWORD_ERROR);
                }
                sysUser = resultUser;
                break;
            case 1://其他平台登陆
                if (StrKit.isBlank(sysUser.getOpenId())) {
                    throw new CustomException(ErrorEnum.PARAMS_LOSE, "openId");
                }
                if (StrKit.isBlank(sysUser.getOpenSource())) {
                    throw new CustomException(ErrorEnum.PARAMS_LOSE, "openSource");
                }
                User params2 = new User();
                params2.setOpenId(sysUser.getOpenId());
                resultUser = sysUserMapper.selectOne(params2);
                if (resultUser == null) {//数据库没有插入一条新的
                    sysUser.setLastLoginTime(new Date());
                    sysUser.setRegisterType(1);
                    sysUser.setOpenSource(sysUser.getOpenSource());
                    sysUser.setSessionKey(sysUser.getSessionKey());
                    Integer r = sysUserMapper.insert(sysUser);
                    if (r != null && r > 0) {
                        return sysUser;
                    } else {
                        throw new CustomException(ErrorEnum.SERVER_ERROR);
                    }
                } else {
                    //用户冻结
                    if (resultUser.getState() != 1) {
                        throw new BusinessException(BusinessExceptionEnum.USER_FROZEN);
                    }
                    sysUser = resultUser;
                }
                break;
        }
        User params3 = new User();
        params3.setId(sysUser.getId());
        params3.setLastLoginTime(new Date());
        sysUserMapper.updateById(params3);//更新最后登陆时间
        sysUser.setPassword(null);
        sysUser.setSessionKey(null);
        sysUser.setOpenId(null);

        return sysUser;
    }


    @Override
    @Transactional
    public Integer updatePassword(Integer id, String newPassword, String confirmPassword) {
        if (id == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE);
        }
        if (StrKit.isBlank(newPassword)) {
            throw new BusinessException(BusinessExceptionEnum.PASSWORD_NULL);
        }
        if (!newPassword.equals(confirmPassword)) {
            throw new BusinessException(BusinessExceptionEnum.PASSWORD_DIFFERENT);
        }
        String md5Password = Md5Util.getSaltMD5(newPassword);
        Integer r = sysUserMapper.updatePassword(id, md5Password);
        if (r != null && r > 0) {
            //发送消息 提醒用户
            Message messageDto = new Message();
            messageDto.setUserId(id);
            messageDto.setType(0);
            messageDto.setContent(MessageConstant.UPDATE_PASSWORD);
            rabbitMqSender.addMessage(messageDto);
            return r;
        } else {
            throw new BusinessException(BusinessExceptionEnum.PASSWORD_UPDATE_FAIL);
        }
    }


    @Override
    @Transactional
    public Integer updatePhone(Integer id, String phone) {
        Integer count = sysUserMapper.selectCount(new EntityWrapper<User>().eq("phone", phone).ne("id", id));
        if (count > 0) {
            throw new BusinessException(BusinessExceptionEnum.USER_PHONE_EXIST);
        }
        count = sysUserMapper.selectCount(new EntityWrapper<User>().eq("phone", phone).eq("id", id));
        if (count > 0) {
            throw new BusinessException(BusinessExceptionEnum.PHONE_UPDATE_EXIST_FAIL);
        }
        User user = new User();
        user.setId(id);
        user.setPhone(phone);
        Integer r = sysUserMapper.updateById(user);
        if (r != null && r > 0) {
            //发送消息 提醒用户
            Message messageDto = new Message();
            messageDto.setUserId(id);
            messageDto.setType(0);
            messageDto.setContent(MessageConstant.UPDATE_PHONE);
            rabbitMqSender.addMessage(messageDto);
            return r;
        } else {
            throw new BusinessException(BusinessExceptionEnum.PHONE_UPDATE_FAIL);
        }
    }

    @Override
    public String getPhone(Integer id) {
        return sysUserMapper.getPhone(id);
    }

}